<?php

/**
 * @package Blog_Filter
 * @version 0.1
 */
 
	add_action('admin_menu', 'blog_filter_create_menu');

	function blog_filter_create_menu() {
		add_options_page('Blog Filter Plugin Settings', 'Blog Filter Settings', 'manage_options', 'blog_filter_options_identifier' , 'blog_filter_settings_page', plugins_url('/images/icon.png', __FILE__));
		add_action( 'admin_init', 'blog_filter_register_settings' );
	}

	function blog_filter_register_settings() {
		register_setting( 'blog-filter-settings-group', 'blog_filter_settings' );
	}
		
	function blog_filter_settings_page() { 

		$current_filters = get_option('blog_filter_settings');
		if ( !is_array($current_filters) ) {
			$current_filters =  array();
		}

		if ( !empty($_POST) && !empty($_POST['filter_name']) ) {
			
			switch( $_POST['action'] ) {
				
				case 'add-filter':
					if ( check_admin_referer('add-filter','_wpnonce') ) {
						$filter_name = sanitize_title($_POST['filter_name']);
						if ( !empty($filter_name) ) {
							$post_per_page = ( empty($_POST['post_per_page']) ) ? get_option('posts_per_page') : (int) $_POST['post_per_page'];
							$current_filters[$filter_name] = array ( 
								'n' => $filter_name,
								'u' => $_POST['user'],
								'c' => $_POST['cat'],
								'h' => (int)$_POST['hl'],
								'p' => $post_per_page,
								'e' => (int)$_POST['paging']
							);
							update_option( 'blog_filter_settings', $current_filters );
						}
						//add_option( 'blog-filter-'.$filter_name.'-html', $_POST['layout'], '', 'yes' );
					}
					
				break;
				
				case 'edit':
					if ( check_admin_referer('edit','_wpnonce') ) {
						$filter_name = $_POST['filter_name'];
						if ( !empty($filter_name) ) {
							$post_per_page = ( empty($_POST['post_per_page']) ) ? get_option('posts_per_page') : (int) $_POST['post_per_page'];
							$current_filters[$filter_name][u] = $_POST['user'];
							$current_filters[$filter_name][c] = $_POST['cat'];
							$current_filters[$filter_name][h] = (int)$_POST['hl'];
							$current_filters[$filter_name][p] = $post_per_page;
							$current_filters[$filter_name][e] = (int)$_POST['paging'];
							update_option( 'blog_filter_settings', $current_filters );
						}
						//update_option( 'blog-filter-'.$filter_name.'-html', $_POST['layout'] );
					}
				break;
				
				case 'delete':
					if ( check_admin_referer('delete','_wpnonce') ) {
						if ( !empty($_POST['filter_name']) ) {
							$diff = array();
							foreach ($current_filters as $settings ) {
								if ( $settings[n] != $_POST['filter_name'] ) {
									array_push($diff, $settings);
								} /*else {
									delete_option('blog-filter-'.$filter_name.'-html');
								}*/
							}
							$current_filters = $diff;
							update_option( 'blog_filter_settings', $current_filters );
						}
					}
				break;
				
			}
			
		}
		
		?>
		
		<?php $categories = get_categories(); ?>
		<?php $users = get_users('orderby=nicename'); ?>
		
		<div class="wrap">
			
			<h2><?php _e('Blog filters') ?></h2>
			
			<div id="col-container">
				
				<div id="col-right">
					<div class="col-wrap">
					<?php if ( $current_filters != null ) { ?>
						
						<h3><?php _e('Active filters') ?></h3>
						
						<table class="wp-list-table widefat fixed posts" cellspacing="0">
							<thead>
								<tr>
									<th><?php _e('Name') ?></th>
									<th><?php _e('Authors') ?></th>
									<th><?php _e('Categories') ?></th>
									<th><?php _e('Paging') ?></th>
									<th><?php _e('Posts per page') ?></th>
									<th><?php _e('Highlight enabled') ?></th>
								</tr>
							</thead>
							<tfoot>
								<tr>
									<th><?php _e('Name') ?></th>
									<th><?php _e('Authors') ?></th>
									<th><?php _e('Categories') ?></th>
									<th><?php _e('Paging') ?></th>
									<th><?php _e('Posts per page') ?></th>
									<th><?php _e('Highlight enabled') ?></th>
								</tr>
							</tfoot>
							<tbody id="the-list" class="list:filter">
							<?php $filter_index = 1; ?>
							<?php foreach ( $current_filters as $value ) { ?>
								<?php $cssClass = ( $cssClass != 'alternate' ) ? 'alternate' : '';?>
								<tr id="filter-<?php echo $filter_index; ?>" class="<?php echo $cssClass; ?>">
									<td>
										<strong>
											<a title="<?php _e('Edit') ?> <?php echo $value['n']; ?>" href="#" class="row-title">
												<?php echo $value['n']; ?>
											</a>
										</strong>
										<div class="row-actions">
											<span class="inline hide-if-no-js">
												<a title="Edit this item inline" class="editinline" href="#">Quick&nbsp;Edit
												</a> | 
											</span>
											<span class="trash">
												<form method="post" style="display:inline;" >
													<input type="hidden" value="<?php echo $value['n']; ?>" name="filter_name">
													<input type="hidden" value="delete" name="action">
													<?php wp_nonce_field('delete','_wpnonce'); ?>
													<input type="submit" value="<?php _e('Delete') ?>" style="color:#BC0B0B;border:none;background:none;margin:0 0 0 -3px;padding:0;font-size:11px;cursor:pointer;" />
												</form>
											</span>
										</div>
										<div id="inline_<?php echo $filter_index ?>" class="hidden">
											<div class="filter_name"><?php echo $value['n'] ?></div>
											<div id="user_<?php echo $filter_index ?>" class="user"><?php if ( is_array($value['u']) ) { echo implode(',', $value['u']); } ?></div>
											<div id="category_<?php echo $filter_index ?>" class="category"><?php if ( is_array($value['c']) ) { echo implode(',', $value['c']); } ?></div>
											<div class="post_per_page"><?php echo $value['p'] ?></div>
											<div class="paging"><?php echo ( $value['e'] == 1 ) ? "open" : ""; ?></div>
											<div class="hl"><?php echo ( $value['h'] == 1 ) ? "open" : ""; ?></div>
											<!--<div class="layout">
												<?php //echo esc_textarea(str_replace('\"', '"', get_option('blog-filter-'.$value['n'].'-html'))) ?>
											</div>-->
										</div>
									</td>
									<td>
										<?php
										if ( is_array($value['u']) ) {
											foreach ( $value['u'] as $u ) {
												echo findUser($users, $u) . ' ';
											}
										}
										?>
									</td>
									<td>
										<?php
										if ( is_array($value['c']) ) {
											foreach ( $value['c'] as $c ) {
												echo findCategory($categories, $c) . ' ';
											}
										}
										?>
									</td>
									<td><?php echo ( $value['e'] == 1 ) ? _e('Yes') : _e('No') ?></td>
									<td><?php echo $value['p'] ?></td>
									<td><?php echo ( $value['h'] == 1 ) ? _e('Yes') : _e('No') ?></td>
								</tr>
								<?php $filter_index++; ?>
							<?php } ?>
							</tbody>
						</table>	
					<?php } ?>
					</div>
				</div>
				
				<div id="col-left">
					<div class="col-wrap">
						<div id="post-body" class="form-wrap">
						
							<h3><?php _e('Add filter') ?></h3>
							
							<form method="post" id="poststuff" >
								
								<input type="hidden" value="add-filter" name="action">
								<?php wp_nonce_field('add-filter','_wpnonce'); ?>
								
								<!-- Filter name -->
								<div class="stuffbox">
									<h3><label for="filter_name"><?php _e('Name') ?></label></h3>
									<div class="inside">
										<input id="filter_name" name="filter_name" type="text" value="">
										<p><?php _e('The filter name which is used in the widget') ?></p>
									</div>
								</div>
								
								<!-- Users -->
								<div id="linkcategorydiv" class="stuffbox">
									<h3 class="hndle"><span><?php _e('Users') ?></span></h3>
									<div class="inside">
										<ul class="category-tabs" id="category-tabs">
											<li class="tabs"><?php _e('All Users') ?></li>
										</ul>
										<div id="categories-all" class="tabs-panel" style="display: block;">
											<ul class="list:category categorychecklist form-no-clear" id="categorychecklist">
												<?php foreach ($users as $user) { ?>
												<li>
													<label class="selectit">
														<input type="checkbox" name="user[]" value="<?php echo $user->ID ?>"> 
														<?php echo $user->display_name ?>
													</label>
												</li>
												<?php } ?>
											</ul>
										</div>
									</div>
								</div>
								
								<!-- Categories -->
								<div id="linkcategorydiv" class="stuffbox">
									<h3 class="hndle"><span><?php _e('Categories') ?></span></h3>
									<div class="inside">
										<ul class="category-tabs" id="category-tabs">
											<li class="tabs"><?php _e('All Categories') ?></li>
										</ul>
										<div id="categories-all" class="tabs-panel" style="display: block;">
											<ul class="list:category categorychecklist form-no-clear" id="categorychecklist">
												<?php foreach ($categories as $category) { ?>
												<li>
													<label class="selectit">
														<input type="checkbox" name="cat[]" value="<?php echo $category->cat_ID ?>"> 
														<?php echo $category->cat_name ?>
													</label>
												</li>
												<?php } ?>
											</ul>
										</div>
									</div>
								</div>
								
								<!-- Paging yes/no -->
								<div class="stuffbox">
									<h3><label for="paging"><?php _e('Paging') ?></label></h3>
									<div class="inside">
										<label class="alignleft inline-edit-private">
											<input type="checkbox" name="paging" value="1" /> 
											<span><?php _e('Yes') ?></span>
										</label>
										<div class="clear"></div>
									</div>
								</div>
								
								<!-- Posts per page -->
								<div class="stuffbox">
									<h3><label for="post_per_page"><?php _e('Posts per page') ?></label></h3>
									<div class="inside">
										<input id="post_per_page" name="post_per_page" type="text" value="">
										<p><?php _e('Amount of posts per page. Defaults to the value set in WordPress settings') ?></p>
									</div>
								</div>
								
								<!-- Highlight yes/no -->
								<div class="stuffbox">
									<h3><label><?php _e('Highlight') ?></label></h3>
									<div class="inside">
										<label class="alignleft inline-edit-private">
											<input type="checkbox" name="hl" value="1" /> 
											<span><?php _e('Yes') ?></span>
										</label>
										<div class="clear"></div>
									</div>
								</div>
								
								<!-- Post layout 
								<div class="stuffbox">
									<h3><label for="layout"><?php //_e('Layout') ?></label></h3>
									<div class="inside">
										<textarea cols="40" rows="5" id="layout" name="layout"></textarea>
										<p><?php //_e('The filter name which is used in the widget') ?></p>
									</div>
								</div>-->
								
								<p class="submit">
									<input type="submit" class="button" value="<?php _e('Add new filter') ?>" />
								</p>
								
							</form>
						</div>
					</div>
				</div>
			</div>
		</div>
		
		<table style="display: none">
			<tbody id="inlineedit">
				<tr style="display: none" class="inline-edit-row" id="inline-edit">
					<td class="colspanchange" colspan="5">
						<form action="" method="post">
						<h4 style="display:block;">Quick Edit</h4>
						
						<fieldset style="width:50%;">
							
							<div class="inline-edit-col">
								<span class="title inline-edit-categories-label">
									<?php _e('Categories') ?>
								</span>
								<ul class="cat-checklist category-checklist">
								<?php foreach ($categories as $category) { ?>
								<li id='category-<?php echo $category->cat_ID ?>'><label class="selectit"><input value="<?php echo $category->cat_ID ?>" type="checkbox" name="cat[]" id="in-category-<?php echo $category->cat_ID ?>" /> <?php echo $category->cat_name ?></label></li>
								<?php } ?>
								</ul>
							</div>
						</fieldset>
						<fieldset style="width:50%;">
							<div class="inline-edit-col">
								<span class="title inline-edit-categories-label">
									<?php _e('Users') ?>
								</span>
								<ul class="cat-checklist user-checklist">
									<?php foreach ($users as $user) { ?>
									<li id='user-<?php echo $user->ID ?>'><label class="selectit"><input value="<?php echo $user->ID ?>" type="checkbox" name="user[]" id="in-category-<?php echo $user->ID ?>" /> <?php echo $user->display_name ?></label></li>
									<?php } ?>
								</ul>
							</div>
						</fieldset>
						<fieldset>
							<div class="inline-edit-col">
								
								<label>
									<span class="title" style="float:none; width:99%;"><?php _e('Posts per page') ?></span>
									<input type="text" value="" class="ptitle" name="post_per_page" />
								</label>
								
								<div class="inline-edit-group">
									<label class="alignleft">
										<input type="checkbox" name="paging" value="1">
										<span class="checkbox-title"><?php _e('Paging') ?> (<?php _e('Yes') ?>) </span>
									</label>
									<label class="alignleft">
										<input type="checkbox" name="hl" value="1">
										<span class="checkbox-title"><?php _e('Highlight') ?> (<?php _e('Yes') ?>) </span>
									</label>
								</div>
								<!--<label>
									<span class="title" style="float:none; width:99%;"><?php _e('Layout') ?></span>
									<textarea cols="40" rows="5" id="layout" name="layout"></textarea>
								</label>-->
							</div>
						</fieldset>
						
						<p class="inline-edit-save submit">
							<input type="hidden" value="edit" name="action">
							<?php wp_nonce_field('edit','_wpnonce'); ?>
							<input type="hidden" value="" name="filter_name">
							<a class="cancel button-secondary alignleft" title="Cancel" href="#inline-edit" accesskey="c">Cancel</a>
							<input type="submit" class="button-primary alignright" value="<?php _e('Update filter') ?>" />
							<br class="clear">
						</p>
						</form>
					</td>
				</tr>
			</tbody>
		</table>
		
			
		<script type="text/javascript">
			(function($) {
				inlineEditTax = {

					init : function() {
						var t = this, row = $('#inline-edit');

						t.type = $('#the-list').attr('className').substr(5);
						t.what = '#'+t.type+'-';

						$('.editinline').live('click', function(){
							inlineEditTax.edit(this);
							return false;
						});

						// prepare the edit row
						row.keyup(function(e) { if(e.which == 27) return inlineEditTax.revert(); });

						$('a.cancel', row).click(function() { return inlineEditTax.revert(); });
						$('a.save', row).click(function() { return inlineEditTax.save(this); });
						$('input, select', row).keydown(function(e) { if(e.which == 13) return inlineEditTax.save(this); });

						$('#posts-filter input[type="submit"]').click(function(e){
							if ( $('form#posts-filter tr.inline-editor').length > 0 )
								t.revert();
						});
					},

					toggle : function(el) {
						var t = this;
						$(t.what+t.getId(el)).css('display') == 'none' ? t.revert() : t.edit(el);
					},

					edit : function(id) {
						var t = this, editRow;
						t.revert();

						if ( typeof(id) == 'object' )
							id = t.getId(id);

						editRow = $('#inline-edit').clone(true), rowData = $('#inline_'+id);
						$('td', editRow).attr('colspan', $('.widefat:first thead th:visible').length);

						if ( $(t.what+id).hasClass('alternate') )
							$(editRow).addClass('alternate');

						$(t.what+id).hide().after(editRow);
						
						$(':input[name="filter_name"]', editRow).val( $('.filter_name', rowData).text() );
						$(':input[name="post_per_page"]', editRow).val( $('.post_per_page', rowData).text() );
						if ( $('.paging', rowData).text() == 'open' )
							$('input[name="paging"]', editRow).attr("checked", "checked");
						if ( $('.hl', rowData).text() == 'open' )
							$('input[name="hl"]', editRow).attr("checked", "checked");
						
						
						//$('textarea', editRow).val($('.layout', rowData).text());
						
						$(editRow).attr('id', 'edit-'+id).addClass('inline-editor').show();
						$('.ptitle', editRow).eq(0).focus();
						
						$('.category', rowData).each(function(){
							var term_ids = $(this).text();

							if ( term_ids ) {
								taxname = $(this).attr('id').replace('_'+id, '');
								$('ul.'+taxname+'-checklist :checkbox', editRow).val(term_ids.split(','));
							}
						});
						
						$('.user', rowData).each(function(){
							var term_ids = $(this).text();

							if ( term_ids ) {
								taxname = $(this).attr('id').replace('_'+id, '');
								$('ul.'+taxname+'-checklist :checkbox', editRow).val(term_ids.split(','));
							}
						});
						
						return false;
					},

					save : function(id) {
						return false;
					},

					revert : function() {
						var id = $('table.widefat tr.inline-editor').attr('id');

						if ( id ) {
							$('table.widefat .inline-edit-save .waiting').hide();
							$('#'+id).remove();
							id = id.substr( id.lastIndexOf('-') + 1 );
							$(this.what+id).show();
						}

						return false;
					},

					getId : function(o) {
						var id = o.tagName == 'TR' ? o.id : $(o).parents('tr').attr('id'), parts = id.split('-');
						return parts[parts.length - 1];
					}
				};

				$(document).ready(function(){inlineEditTax.init();});
			})(jQuery);
		</script>
	<?php 

	} 

	function findUser($arr, $id) {
		if ( $id != null ) {
			foreach ($arr as $user) {
				if ( $user->ID == $id )
					return $user->display_name;
			}
		}
		return '';
	}
	
	function findCategory($arr, $id) {
		if ( $id != null ) {
			foreach ($arr as $category) {
				if ( $category->cat_ID == $id ) {
					return $category->cat_name;
				}
			}
		}
		return '';
	}

?>